<?php
// +----------------------------------------------------------------------
// | 随访系统
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2050 http://www.hedesoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +---------------------------------------------------------------------
// | Author: 小李子 < 490959289@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;
use app\admin\controller\Base;
use think\Validate;
class Mould extends Base
{
    public function index()
    {
        $model=model('Moulds');
        $list=$model::getMouldList();
        // 获取分页显示
        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);
    	return $this->fetch();
    }
    //加载添加/编辑页
    public function add_mould(){
    $model=model('Moulds');
    $id = $this->request->param('id');
    $data = $model::getMouldInfo($id);
    if(!empty($data->attribute))$data->attr_id=explode('|',$data->attribute);
    $this->assign('data', $data);

    $list=model('Category')->where('pid',0)->select();
    $this->assign('list', $list);

    $attrs=model('Attr')->getAttrList();
    $this->assign('attrs', $attrs);
    return $this->fetch();
    }

    //数据保存
    public function save_data(){
        $model=model('Moulds');

        $rule = [
        'c_id'  => 'require',
        'price'  => 'require',
        'images'  => 'require',
        ];

        $msg = [
            'c_id.require' => '请选择分类',
            'price.require' => '请填写价格',
            'images.require' => '请上传主图'
        ];

        $data['c_id'] = $this->request->param('c_id');
        $data['price'] = $this->request->param('price');
        $data['images'] = $this->request->param('images');
        $data['html_url'] = $this->request->param('html_url');
        $data['source'] = $this->request->param('source');
        $data['is_index'] = $this->request->param('is_index');
        $data['is_sale'] = empty($data['html_url'])?0:$this->request->param('is_sale');//未上传模版文件不能发布模版

        $validate = new Validate($rule, $msg);
        if (!$validate->check($data)){
            echo json_encode(array('status'=>0,'msg'=>$validate->getError()));exit;
        }

        $id = $this->request->param('id');
        $data['add_time'] = time();
        $data['attribute'] =$this->getAttrStr($this->request->param('attr_id/a'));
        $number=$this->request->param('number');
        $data['number'] =$number?$number:$this->getNumberStr();


        //解压文件
        $type_wj = pathinfo($data['html_url'], PATHINFO_EXTENSION); //获取文件类型
        //判断文件类型
        $dir=ROOT_PATH . 'moban';
        if(strtolower($type_wj) == "zip" || strtolower($type_wj) == "rar"){
            if(strtolower($type_wj) == "zip"){
                //解压zip文件
                $this->unzip_file($data['html_url'],$dir);
            }else{
                //解压rar文件
                $this->unrar($data['html_url'],$dir);
            }

            $data['html_url']=$dir.DS. strstr( basename($data['html_url']), '.', TRUE );
        }

        if ($id){
            $status = $model->where('id',$id)->update($data);
        }else{
            $status = $model->insertGetId($data);
        }
        if(empty($status)){
            echo json_encode(array('status'=>0,'msg'=>'保存失败'));exit;
        }

        echo json_encode(array('status'=>1,'msg'=>'保存成功'));
    }


    //删除模版
    public function delMould()
    {
        $model=model('Moulds');
        $data['id'] = $this->request->param('id');
        $status = $model->where($data)->delete();

        if ($status){
            echo json_encode(['status'=>1,'msg'=>'删除成功']);exit();
        }else{
            echo json_encode(['status'=>0,'msg'=>'删除失败']);exit();
        }
    }

    //文件上传
    function upload(){
        $file = $this->request->file('file');
        $file->rule('time');

        $filename = $file->getInfo('name');
        $filetype = explode('/',$file->getInfo('type'));

        if($filetype[0]=='image'){
            $dirname=date('Ymd');
            $filename=time();
        }else {$dirname = strstr( $filename, '.', TRUE );}
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $dirname,$filename);
        $path = 'uploads/'.$dirname.'/'.$info->getFilename();

        if ($path) {
            return $path;
        } else {
            //是专门来获取上传的错误信息的
            //$this->error($upload->getErrorMsg());
            //echo $upload->getErrorMsg();
            return false;
        }

    }

    //属性id字符串
    function getAttrStr($attr_array){
        if(empty($attr_array)){
            return '';
        }
        sort($attr_array);
        $attr_str=implode('|',$attr_array);
        return $attr_str;
    }
    //生成模版编号
    function getNumberStr(){
        return date('M').time();
    }

    /**
     * 模版发布
     */
    function setSale(){
        $model=model('Moulds');

        $id=$this->request->param('id');
        $sale_value=$this->request->param('sale_value');

        $status=$model->save([
            'is_sale'  => $sale_value
        ],['id' => $id]);

        if ($status) {
            echo json_encode(['status' => 1]);die;
        }

        echo json_encode(['status' => 0, 'msg' => '发布失败！']);die;

    }


    /*  PHP解压缩 Zip 文件@file - path to zip file *@destination - destination directory for unzipped files */
    public function unzip_file($file, $dir){

        // 实例化对象
        $zip = new \ZipArchive() ;
        //打开zip文档，如果打开失败返回提示信息
        if ($zip->open($file) !== TRUE) {
            die ("Could not open archive");
        }
        //将压缩文件解压到指定的目录下
        $zip->extractTo($dir);
        //关闭zip文档
        $zip->close();

    }

    /**
     * 解压rar文件
     */
    public function unrar($file,$dir){

        $obj = new \com("WScript.Shell");
        if($obj){
            $obj->run('winrar x '.$file.' '.$dir, 0, true);
            return true;
        }else{
            return false;
        }
        $obj->Quit();
        $obj->Release();
        $obj = null;
    }

    /**清除解压文件及文件夹**/
    function deldir($dir){
        //先删除目录下的文件：

        $dh=opendir($dir);

        while ($file=readdir($dh)) {

            if($file!="." && $file!="..") {

                $fullpath=$dir."/".$file;

                if(!is_dir($fullpath)) {
                    unlink($fullpath);
                } else {
                    deldir($fullpath);
                }

            }

        }

        closedir($dh);

        //删除当前文件夹：

        if(rmdir($dir)) {

            return true;

        } else {

            return false;

        }
    }
}
